package compositeExpression_Fact;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.StringTokenizer;
import visitor.Visitor;
import compositeExpression.Expression;
import compositeExpression.Fact;
import exceptions.IllegalContextException;

public class FactId extends Fact {
	
	 private String id;
	 private int num;
	 
	 public FactId(String id) {

	        this.id = id;
	        num = 0;
	    }
	 
	 public int getState() {

	        return num;
	    }// getStato

	@Override
	public void toAssess(String p) throws IllegalContextException {
		
		File f = new File(p);

        try {

            BufferedReader in = new BufferedReader(new FileReader(f));
            String linea;

            while (true) {

                try {

                    linea = in.readLine();

                    if (linea == null) {// condizione uscita dal while

                        in.close();
                        break;
                    }

                    StringTokenizer st = new StringTokenizer(linea, "=");
                    String temp;

                    while (st.hasMoreTokens()) {

                        temp = st.nextToken();

                        if (id.equalsIgnoreCase(temp)) {// valore di factId

                            num = (Integer.parseInt(st.nextToken()));
                            break;
                        }
                    }


                } catch (IOException ex) {

                    System.out.println("Attezione, si e' verificato un errore di lettura.");
                    in.close();
                    System.exit(-1);
                }

            }

            in.close();
        } catch (FileNotFoundException ex) {

            System.out.println("Attenzione, file " + p + " non trovato.");
            System.exit(-1);
        } catch (IOException ex) {

            System.out.println("Attenzione, lettura interrotta");
            System.exit(-1);
        }

	}

	@Override
    public void accept(Visitor v) {
        v.visit(this);
    }
	
	
	@Override
	public void add(Expression termb) {
		throw new IllegalStateException("operazione non supportata");
	}
	
	  @Override
	    public String toString() {

	        StringBuilder sb = new StringBuilder();

	        return sb.append(num).toString();
	    }

}
